'use strict';
const crypto = require('crypto');

// 生成token
const generateToken = () => {
  const timestamp = Date.now();
  const randomStr = crypto.randomBytes(16).toString('hex');
  return crypto.createHash('sha256')
    .update(`${timestamp}${randomStr}`)
    .digest('hex');
};

// 验证管理员账号密码
const verifyAdmin = async (username, password) => {
  try {
    const db = uniCloud.database();
    const { data } = await db.collection('admin').where({
      username: username,
      password: crypto.createHash('sha256').update(password).digest('hex')
    }).get();
    
    return data && data.length > 0;
  } catch (error) {
    console.error('验证管理员账号失败:', error);
    return false;
  }
};

exports.main = async (event, context) => {
  const { username, password } = event;
  
  if (!username || !password) {
    return {
      success: false,
      message: '用户名和密码不能为空'
    };
  }
  
  try {
    // 验证管理员账号密码
    const isValid = await verifyAdmin(username, password);
    
    if (!isValid) {
      return {
        success: false,
        message: '用户名或密码错误'
      };
    }
    
    // 生成token
    const token = generateToken();
    
    // 更新管理员token
    const db = uniCloud.database();
    await db.collection('admin').where({
      username: username
    }).update({
      token: token,
      lastLoginTime: Date.now(),
      lastLoginIP: context.CLIENTIP
    });
    
    return {
      success: true,
      token: token,
      message: '登录成功'
    };
  } catch (error) {
    console.error('管理员登录失败:', error);
    return {
      success: false,
      message: '登录失败，请稍后重试'
    };
  }
}; 